import axios from 'axios'
const listStore = {
  // 使其成为带命名空间的模块。当模块被注册后，它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名
  // 不添加，默认是注册在全局命名空间的
  // https://vuex.vuejs.org/zh/guide/modules.html
  namespaced: true,
  state: () => ({
    // 所有的任务列表
    list: [],
    inputVal: 'aaa',
    viewKey: 'all'
  }),
  mutations: {
    initList (state, list) {
      state.list = list
    },
    setInputVal (state, val) {
      state.inputVal = val
    },
    addItem (state) {
      const obj = {
        id: state.list[state.list.length - 1].id + 1,
        info: state.inputVal,
        done: false
      }
      state.list.push(obj)
      state.inputVal = ''
    },
    deleteItem (state, id) {
      const i = state.list.findIndex(x => x.id === id)
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    changeStatus (state, param) {
      const i = state.list.findIndex(x => x.id === param.id)
      if (i !== -1) {
        state.list[i].done = param.status
      }
    },
    cleanDone (state) {
      state.list = state.list.filter(x => x.done === false)
    },
    changeViewKey (state, key) {
      state.viewKey = key
    }
  },
  actions: {
    async getList ({ state, commit, rootState }) {
      const { data } = await axios.get('/list.json')
      // console.log(data)
      commit('initList', data)
    }
  },
  getters: {
    unDoneLength (state) {
      return state.list.filter(x => x.done === false).length
    },
    viewUi (state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'done') {
        return state.list.filter(x => x.done === true)
      }
      if (state.viewKey === 'undone') {
        return state.list.filter(x => x.done === false)
      }
      return state.list
    }
  },
  modules: {
  }
}
export default listStore
